package xin.nick.cloud.user.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.nick.cloud.pojo.Token;
import xin.nick.cloud.pojo.User;
import xin.nick.cloud.service.CodeService;
import xin.nick.cloud.user.client.ServiceCodeClient;
import xin.nick.cloud.user.dao.TokenDao;
import xin.nick.cloud.user.dao.UserDao;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @author Nick
 * @date 2021/8/1
 * @description
 */
@RestController
@Slf4j
public class UserController {

    private static final String TOKEN_NAME = "token";


    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Reference
    private CodeService codeService;

    /**
     * 注册接⼝，true成功，false失败
     * @param email
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/user/register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code,
                            HttpServletResponse response) {

        log.info("注册用户来啦~ {}:{}:{}",email, password, code);

        // 判断验证码正确吗
        int validateStatus = codeService.validate(email, code);

        if (1 != validateStatus) {
            return false;
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userDao.save(user);
        // 存token
        String tokenValue = UUID.randomUUID().toString();
        Token token = new Token();
        token.setToken(tokenValue);
        token.setEmail(email);
        tokenDao.save(token);

        // 设置cookie的token
        Cookie cookie = new Cookie(TOKEN_NAME, tokenValue);
        cookie.setMaxAge(60*60);
        cookie.setPath("/");
        response.addCookie(cookie);

        return true;
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     * @param email
     * @return
     */
    @RequestMapping("/user/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        log.info("这个用户注册了吗~ {}",email);
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        Optional<User> one = userDao.findOne(example);
        if (one.isEmpty() || Objects.isNull(one.get())) {
            return false;
        }
        return true;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email
     * @param password
     * @return
     */
    @RequestMapping("/user/login/{email}/{password}")
    public String login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response) {
        log.info("用户登录来了 {}:{}",email, password);
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Example<User> example = Example.of(user);
        Optional<User> one = userDao.findOne(example);
        if (one.isEmpty() || Objects.isNull(one.get())) {
            return "fail";
        }
        user = one.get();
        String returnEmail = user.getEmail();

        // 存token
        String tokenValue = UUID.randomUUID().toString();
        Token token = new Token();
        token.setToken(tokenValue);
        token.setEmail(returnEmail);
        tokenDao.save(token);

        // 设置cookie的token
        Cookie cookie = new Cookie(TOKEN_NAME, tokenValue);
        cookie.setMaxAge(60*60);
        cookie.setPath("/");
        response.addCookie(cookie);

        return returnEmail;

    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     * @return
     */
    @RequestMapping("/user/info")
    public String info(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        Cookie cookie = cookies[0];
        String tokenValue = cookie.getValue();
        String token = tokenValue;
        log.info("你也是来用token拿邮箱的吗: {}", token);

        Token tokenQuery = new Token();
        tokenQuery.setToken(token);
        Example<Token> example = Example.of(tokenQuery);
        Optional<Token> one = tokenDao.findOne(example);
        if (one.isEmpty() || Objects.isNull(one.get())) {
            return "fail";
        }
        return one.get().getEmail();
    }

}
